<?php
/**
 * 这个类配置首页相关的和未归类的控制器
 */
class Bookiki extends Controller
{
	var $totalrows=-1;  //因为不同函数实例化不同bookiki对象，所以使用一个totalrows变量就可以。
    function Bookiki()
	{
		parent::Controller();
        $this->load->model('book_model');
        $this->load->model('user_model');
        $this->load->model('post_model');
        $this->load->model('school_model');
        $this->load->library('session');
        $this->load->library('mypagination');
        //$this->output->enable_profiler(TRUE); //CI的自动报告网站状态函数
        //$this->output->cache(1);   //cache the page for n minutes
	}

    /**
     * 调用首页视图的控制函数
     */
	function index()
	{
	$data['title'] = "书易Bookiki-校园二手书交易更容易"; //浏览器标题栏标题
	$data['activetab']="home"; //导航栏上显示为绿色的tab
    list($schoolsetstatus,$school)=$this->user_model->get_schoolinitial();
    if($schoolsetstatus==0){   //session中没有设置学校
          //以下这段代码是根据IP地址来判断用户所在学校的
           $ipstr=$_SERVER['REMOTE_ADDR'];
           $ipstr=trim($ipstr);
           $ips=split('[.]' , $ipstr);
           $ip_num=16777216 * $ips[0] + 65536 * $ips[1] + 256* $ips[2] + $ips[3];
           $result=$this->school_model->choose_school_byip($ip_num);
           if($result==0) {//session没有，IP又无法识别，只能匹配浙大这个默认结果
              /*$this->session->set_userdata('schoolinitials', "ahu");
              $this->session->set_userdata('school_id', "6");
              $this->session->set_userdata('schoolname', "安徽大学");
              $school="ahu";
              print "ahu";*/
              $this->session->set_userdata('schoolinitials', "zju");
              $this->session->set_userdata('school_id', "599");
              $this->session->set_userdata('schoolname', "浙江大学");
              $school="zju";
           }
           else{
              $schoolresult=$result[0];
              //echo $schoolresult->school_name;
              $this->session->set_userdata('schoolinitials', $schoolresult->school_initials);
              $this->session->set_userdata('school_id', $schoolresult->school_id);
              $this->session->set_userdata('schoolname', $schoolresult->school_name);
              $school=$schoolresult->school_initials;
           }
    }
    $data['user_status']=$this->user_model->get_user_status(); //获取用户登录状态
    $data['recent_salepost']=$this->post_model->getlatest_salepost(0,$school,0,12);  //获取最近发布的销售图书信息
    $data['recent_wantedpost']=$this->post_model->getlatest_wantedpost(0,$school,0,11);  //获取最近发布的求购图书信息
    $data['hottest_book']=$this->book_model->get_hottest_book(0,0,10); //获取最热图书
    $data['hottest_shop']=$this->user_model->get_shops(0,$school,-1,0,5); //campusid=-1
    $this->load->view('bookiki/index', $data);
	}

   /**
    * 这个函数用来在数据库中大量创建表格，是后台操作，只能通过浏览器地址访问
    */
   /*function createschool(){
        $status=$this->school_model->create_alltables();
        if($status==1)
          $this->index();
        else
          echo "error";
    }
    */

	/**
     * 这个函数实现搜索建议功能
     */
    function ajaxsearch()
	{
        $this->load->library('validation');

        $rules['inputString']='htmlspecialchars|urldecode|xss_clean';
        $this->validation->set_rules($rules);

        $fields['inputString']='inputString';
        $this->validation->set_fields($fields);

        if($this->validation->run())
        {
            $query=$this->validation->inputString;
            $result=$this->book_model->getQuerySuggestion($query);
            if(!empty($result))
            {
                foreach($result as $suggestion)
                {
                    echo($suggestion."\n");
                }
            }
        }
	}

    /**
     *书籍搜索的控制器，在对搜索查询词进行无效字符清理后，调用book_model->bookSearchResults（）进行书籍的搜索。
     */
    function search()
	{
		/*$this->load->library('validation');
        $rules['inputString']='htmlspecialchars|urldecode|xss_clean';
        $this->validation->set_rules($rules);
        $fields['inputString']='inputString';
        $this->validation->set_fields($fields);
        if($this->validation->run())
           $inputString=$this->validation->inputString;*/
        $inputString=$this->input->get('inputStringBottom',TRUE);
        if($inputString==null)
        $inputString=$this->input->get('inputString',TRUE);
        $inputString=urldecode($inputString);
        $inputString=trim($inputString);
        if($inputString==NULL){   //如果经过前面一些列的清理，表明query只是诸如空格或tab等无效字符，则跳回首页
          $this->index();
          return;
        }

        //配置分页函数
        if(isset($_GET['curpage']))
           $offset=$_GET['curpage'];
        else
           $offset=0;
         if(!isset($_GET['totalrows'])){
           $result= $this->book_model->bookSearchResults($inputString,1,$offset,12);
           $config['total_rows'] =$result[0]->number;
        }
        else{
           $config['total_rows'] =$_GET['totalrows'];
        }
        $config['page_query_string'] = TRUE;
        $link="bookiki/search?inputString=$inputString&totalrows={$config['total_rows']}";
        $config['base_url'] = site_url($link);
        $config['full_tag_open'] = '<p>';
        $config['full_tag_close'] = '</p>';
        $config['per_page']=12;
        $this->mypagination->initialize($config);
        $data['bookarray'] = $this->book_model->bookSearchResults($inputString,0,$offset,12); //调用模型中函数搜索
        $data['title'] = "书易图书搜索结果：";
        $data['activetab']="none";
        $data['user_status']=$this->user_model->get_user_status(); //获取用户登录状态
        $this->load->view('bookiki/search', $data);
	}

    /**
     * 从首页进入高级搜索的入口控制器
     */
    function advancedSearchInput()
	{
        $data['title'] = "书易高级图书搜索：";
        $data['activetab']="none";
		$data['user_status']=$this->user_model->get_user_status(); //获取用户登录状态
        $this->load->view('bookiki/advancedSearch', $data);
	}


    /**
     * 在高级搜索页面调用数据库进行搜索的控制器
     */
    function advancedSearch()
	{
        $title=$_GET['title'];
        $en_title=$_GET['en_title'];
        $author=$_GET['author'];
        $publisher=$_GET['publisher'];
        $edition=$_GET['edition'];
        $language=$_GET['language'];

        if(isset($_GET['curpage']))
           $offset=$_GET['curpage'];
        else
           $offset=0;
         if(!isset($_GET['totalrows'])){
           $result= $this->book_model->advancedSearch(1,$offset,12,$title,$en_title,$author,$publisher,$edition,$language);
           $config['total_rows'] =$result[0]->number;
        }
        else{
           $config['total_rows'] =$_GET['totalrows'];
        }
        $config['page_query_string'] = TRUE;
        $link="bookiki/advancedSearch?title=$title&en_title=$en_title&author=$author&publisher=$publisher&edition=$edition&language=$language&totalrows={$config['total_rows']}";
        $config['base_url'] = site_url($link);
        $config['full_tag_open'] = '<p>';
        $config['full_tag_close'] = '</p>';
        $this->mypagination->initialize($config);
        $data['bookarray']=$this->book_model->advancedSearch(0,$offset,12,$title,$en_title,$author,$publisher,$edition,$language);
        $data['title'] = "书易二手书高级搜索结果：";
        $data['activetab']="none";
		$data['user_status']=$this->user_model->get_user_status(); //获取用户登录状态
        $this->load->view('bookiki/search', $data);
	}

    /**
     * 进行书单的自动匹配。也就是说，根据用户发布的供求信息进行匹配，以求两个用户能尽量多的交易书籍
     */
    function automatch(){
        $username=$this->session->userdata('username');
        $siteurl=site_url();
        //$currentPage=$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
        $currentPage=$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
        if($username==""){
            $loginPage=$siteurl.'/user/login?continue=yes&currentpage='.urlencode($currentPage);
            Header("Location: $loginPage");
        }
        list($schoolsetstatus,$school)=$this->user_model->get_schoolinitial();
        $data['matched_user']=$this->post_model->auto_match($username,$school);
        //调用广告模型中的函数，并将参数以数组的形式传递过去，返回匹配的*用户*
        $data['activetab']="automatch";
        $data['title']="书单自动匹配";
		$data['user_status']=$this->user_model->get_user_status(); //获取用户登录状态
        $this->load->view('automatch_view',$data);
    }

     /**
      * 返回书单匹配中，两个用户的*具体书籍*匹配结果
      */
     function automatch_detail(){
        $username=$this->session->userdata('username');  //当前登录帐户的用户名
        $siteurl=site_url();
        $currentPage=$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
        if($username==""){
            $loginPage=$siteurl.'/user/login?continue=yes&currentpage='.urlencode($currentPage);
            Header("Location: $loginPage");
        }
        $matched_user=$_GET['matched_user']; //与当前帐户相匹配的用户名
        list($schoolsetstatus,$school)=$this->user_model->get_schoolinitial();
        $data['user']=$this->user_model->get_userinfo($matched_user);
        $data['school'] = $this->user_model->get_schoolname($data['user']->school_id);
        $data['campus'] =$this->user_model->get_campus($data['user']->campus_id);
        $dataarray=$this->post_model->automatch_detail($username,$matched_user,$school);
        //调用广告模型中的函数，并将参数以数组的形式传递过去,返回两个用户的*具体书籍*匹配结果
        $data['saleposts']=$dataarray['saleposts'];
        $data['wantedposts']=$dataarray['wantedposts'];
        if(isset($_GET['contact'])){
            if($this->session->userdata('username')==""){
               $siteurl=site_url();
               $currentPage=$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
               $loginPage=$siteurl.'/user/login?continue=yes&currentpage='.urlencode($currentPage);
               header("Location: $loginPage");
            }
          $data['contact']=$_GET['contact'];
        }
        else $data['contact']="none";
        $data['activetab']="automatch";
        $data['title']="与".$matched_user."的书单匹配细节";
		$data['user_status']=$this->user_model->get_user_status(); //获取用户登录状态
        $this->load->view('bookiki/bookshop_detail_view',$data);
    }

    /**
     * 废弃，现在功能已经整合到automatch_detail()函数中
     */
    /*function wanted_matchdetail(){
        $username=$this->session->userdata('username');
        $siteurl=site_url();
        $currentPage=$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
        if($username==""){
            $loginPage=$siteurl.'/user/login?continue=yes&currentpage='.urlencode($currentPage);
            Header("Location: $loginPage");
        }
        list($schoolsetstatus,$school)=$this->user_model->get_schoolinitial();
        $data['posts']=$this->post_model->wanted_matchdetail($username,$_GET['wanted_user'],$school);
        $data['activetab']="automatch";
        $data['title']="书单自动匹配";
		$data['user_status']=$this->user_model->get_user_status(); //获取用户登录状态
        $this->load->view('wanted_matchdetail_view',$data);
     }
     */

     /**
     * 废弃，现在功能已经整合到automatch_detail()函数中
     */
     /*
     function sale_matchdetail(){

        $username=$this->session->userdata('username');
        $siteurl=site_url();
        $currentPage=$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
        if($username==""){
            $loginPage=$siteurl.'/user/login?continue=yes&currentpage='.urlencode($currentPage);
            Header("Location: $loginPage");
        }
        list($schoolsetstatus,$school)=$this->user_model->get_schoolinitial();
        $data['posts']=$this->post_model->sale_matchdetail($username,$_GET['sale_user'],$school); 
        $data['activetab']="automatch";
        $data['title']="书单自动匹配";
		$data['user_status']=$this->user_model->get_user_status(); //获取用户登录状态
        $this->load->view('sale_matchdetail_view',$data);
     }
     */

    /**
     * 转向"逛书店”功能的控制器，可以根据校区浏览书店
     */
    function bookshop(){
         if(isset($_GET['campusid'])&&$_GET['campusid']!=null)
           $campusid=$_GET['campusid'];
        else
           $campusid=-1;
        //配置分页函数
        if(isset($_GET['curpage']))
           $offset=$_GET['curpage'];
        else
           $offset=0;
        $config['page_query_string'] = TRUE;
        list($schoolsetstatus,$school)=$this->user_model->get_schoolinitial();
        if(!isset($_GET['totalrows'])){
              $result=$this->user_model->get_shops(1,$school,$campusid,$offset,15);
              $config['total_rows'] =$result[0]->number;
        }
        else
           $config['total_rows'] =$_GET['totalrows'];
        $link="bookiki/bookshop?go=yes&totalrows={$config['total_rows']}&campusid=$campusid";
        $config['base_url'] = site_url($link);
        $config['full_tag_open'] = '<p>';
        $config['full_tag_close'] = '</p>';
        $config['per_page']=15;
        $this->mypagination->initialize($config);
        $shops = $this->user_model->get_shops(0,$school,$campusid,$offset,15);
        if($shops!=null){
          foreach($shops as $shop){
             $shop->campus=$this->user_model->get_campus($shop->campus_id);
           }
        }
        $data['shops']=$shops;
        $schoolid=$this->user_model->get_schoolid();
        $data['allcampus']=$this->user_model->get_campus_ofschool($schoolid);
        $data['campusid']=$campusid;
        $data['activetab']="bookshop";
        $data['title']="逛书店";
        $data['user_status']=$this->user_model->get_user_status(); //获取用户登录状态
        $this->load->view('bookiki/bookshop_view',$data);
    }

    /**
     * 在“逛书店”页面找到书店后进入
     */
    function enterShop(){
        $userid=$_GET['id'];
        //$school=$_POST['school_initials'];
        list($schoolsetstatus,$school)=$this->user_model->get_schoolinitial();
        $dataarray=$this->user_model->enterShop($userid,$school);  //调用用户模型中的函数，并将参数以数组的形式传递过去
        $data['user']=$this->user_model->get_userinfo($userid);
        $data['school'] = $this->user_model->get_schoolname($data['user']->school_id);
        $data['campus'] =$this->user_model->get_campus($data['user']->campus_id);
        $data['saleposts']=$dataarray['saleposts'];
        $data['wantedposts']=$dataarray['wantedposts'];
        if(isset($_GET['contact'])){
            if($this->session->userdata('username')==""){
               $siteurl=site_url();
               $currentPage=$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
               $loginPage=$siteurl.'/user/login?continue=yes&currentpage='.urlencode($currentPage);
               header("Location: $loginPage");
            }
          $data['contact']=$_GET['contact'];
        }
        else $data['contact']="none";
        $data['activetab']="bookshop";
        $data['title']="逛书店";
		$data['user_status']=$this->user_model->get_user_status(); //获取用户登录状态
        $this->load->view('bookiki/bookshop_detail_view',$data);
    }
    
    /**
     * 中文“关于”页面的控制器
     */
    function about()
    {
        $data['title'] = "关于书易";
        $data['activetab']="none";
        $data['user_status']=$this->user_model->get_user_status(); //获取用户登录状态
        $this->load->view('bookiki/about', $data);
    }

    /**
     * 英文“关于”页面的控制器
     */
	function about_eng()
    {
        $data['title'] = "About Bookiki";
        $data['activetab']="none";
        $data['user_status']=$this->user_model->get_user_status(); //获取用户登录状态
        $this->load->view('bookiki/about_eng', $data);
    }
    

    /**
     * 帮助页面的控制器
     */
    function faq()
    {
        $data['title'] = "使用帮助";
        $data['activetab']="none";
        $data['user_status']=$this->user_model->get_user_status(); //获取用户登录状态
        $this->load->view('bookiki/faq', $data);
    }
}
?>
